<template>
  <div class="container">
    <h2>扫码数据管理</h2>

    <!-- 时间范围选择 -->
    <el-form :inline="true" class="filter-form">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="queryData">查询</el-button>
        <el-button type="danger" @click="deleteData">删除</el-button>
        <el-button type="success" @click="exportData">导出 Excel</el-button>
      </el-form-item>
    </el-form>

    <!-- 查询结果表格 -->
    <el-table v-if="tableData.length > 0" :data="tableData" border style="width: 100%; margin-top: 20px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="group_id" label="组号" width="100" />
      <el-table-column prop="package_code" label="翻包二维码" />
      <el-table-column prop="supplier_code" label="供应商二维码" />
      <el-table-column prop="result" label="比对结果" width="120" />
      <el-table-column prop="timestamp" label="扫描时间" width="200" />
    </el-table>

    <div v-else style="margin-top: 20px; color: gray">
      暂无数据，请选择时间范围后查询。
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const timeRange = ref(null); // [开始时间, 结束时间]
const tableData = ref([]);

// 电脑端 FastAPI 服务地址
const API_BASE = "http://127.0.0.1:8000/api";

// helper: Date -> "YYYY-MM-DD HH:mm:ss"
function formatDateForQuery(d) {
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  const hours = String(d.getHours()).padStart(2, "0");
  const minutes = String(d.getMinutes()).padStart(2, "0");
  const seconds = String(d.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 获取今天 00:00:00 ~ 23:59:59
function getTodayRange() {
  const now = new Date();
  const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
  const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
  return [formatDateForQuery(start), formatDateForQuery(end)];
}

// 从 timeRange 获取 start/end，若为空则返回今天
function getStartEndFromTimeRange() {
  const v = timeRange.value;
  if (Array.isArray(v) && v.length === 2) {
    return v;
  }
  return getTodayRange();
}

// 查询数据
const queryData = async () => {
  try {
    const [start, end] = getStartEndFromTimeRange();
    const url = `${API_BASE}/query?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}`;
    const res = await fetch(url);
    if (!res.ok) throw new Error(`查询失败: ${res.status}`);
    tableData.value = await res.json();
    ElMessage.success(`查询到 ${tableData.value.length} 条数据`);
  } catch (err) {
    console.error(err);
    ElMessage.error(err.message || "查询失败");
  }
};

// 删除数据
const deleteData = async () => {
  try {
    const [start, end] = getStartEndFromTimeRange();
    await ElMessageBox.confirm(
      `确定要删除 ${start} 至 ${end} 的数据吗？此操作不可恢复！`,
      "警告",
      { type: "warning" }
    );
    const url = `${API_BASE}/delete?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}`;
    const res = await fetch(url, { method: "DELETE" });
    if (!res.ok) throw new Error(`删除失败: ${res.status}`);
    const data = await res.json();
    ElMessage.success(`已删除 ${data.deleted} 条数据`);
    tableData.value = [];
  } catch (err) {
    if (err !== "cancel") {
      console.error(err);
      ElMessage.error(err.message || "删除失败");
    }
  }
};

// 导出数据
const exportData = async () => {
  try {
    const [start, end] = getStartEndFromTimeRange();
    const url = `${API_BASE}/export?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}`;
    window.open(url, "_blank");
    ElMessage.success("导出任务已开始，请检查下载");
  } catch (err) {
    console.error(err);
    ElMessage.error(err.message || "导出失败");
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}
.filter-form {
  margin-bottom: 20px;
}
</style>
